/* eslint-disable */
//
// FileName ArrayExtend
// ProjectName web
// ComputerUser gys
// Author 区区电脑
// Email 1573580882@qq.com
// Date 2021/5/4 1:45 下午
// Copyright © 2021 gys. All rights reserved.


/**
 * 树遍历
 */
Array.prototype.treeMap =
    Array.prototype.treeMap ||
    function (callback, children = "children") {
        if (!callback) {
            console.error("arg is not find");
            return 0;
        }
        const array = this;

        function func(array, callback, children) {
            for (let i = 0; i < array.length; i++) {
                const item = array[i];
                callback(item);
                if (item[children] && item[children].length > 0) {
                    func(item[children], callback, children);
                }
            }
        }

        func(array, callback, children);
    };

/**
 * 数组转树
 * @param key
 * @param pKey
 * @param children
 * @returns {*[]}
 */
Array.prototype.toTree = function (key = "id", pKey = "pId", children = "children") {
    const map = {};
    const result = [];
    this.forEach(item => {
        map[item[key]] = {...item, [children]: []};
    });
    this.forEach(item => {
        const parent = map[item[pKey]];
        if (parent) {
            parent[children].push(map[item[key]]);
        } else {
            result.push(map[item[key]]);
        }
    });
    return result;
}

/**
 * 树查找
 * @param callback
 * @param children
 * @returns {*|null}
 */
Array.prototype.treeFind = function (callback, children = "children") {
    const stack = [...this];
    while (stack.length > 0) {
        const node = stack.pop();
        if (callback(node)) {
            return node;
        }
        stack.push(...node[children]);
    }
    return null;
}

Array.prototype.treeMap2 = function (callback, children = "children") {
    let result = null;
    const stack = [...this];
    while (stack.length > 0) {
        const node = stack.pop();
        // 调用外部传入的回调函数处理当前节点，并更新结果
        result = callback(node, result);
        stack.push(...node[children]);
    }
    return result;
}